/*
 * Copyright 2010 Eligio Colutta
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package com.google.code.p2pxmppclient;

import java.util.logging.Logger;

import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import com.google.code.p2pxmppclient.executers.CommandExecuter;
import com.google.code.p2pxmppclient.executers.amule.AmulecmdExecuter;


/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public class XMPPPacketListener implements PacketListener {
	private static final Logger log = Logger.getLogger(XMPPPacketListener.class.getCanonicalName());
	
	private XMPPConnection xmppConnection;
	
	public XMPPPacketListener(XMPPConnection conn) {
        xmppConnection = conn;
    }
	
	@Override
	public void processPacket(Packet packet) {
        Message message = (Message)packet;
        if(message.getBody() != null) {
        	String fromName = StringUtils.parseBareAddress(message.getFrom()); 
        	String body = message.getBody();
        	log.info("New message from " + fromName + ": " + body );
        	String returnMessage = "";
        	try {
        		 returnMessage = getExecuter(body).executeCommand(body);
			} catch (Exception e) {
				returnMessage = "ERRORE: " + e.getLocalizedMessage();
			}
			if(returnMessage.equals("")){
				returnMessage = "<NO RESPONSE>";
			}
            Message reply = new Message();
            reply.setTo(fromName);
            reply.setBody(returnMessage);
            xmppConnection.sendPacket(reply);
        }
	}
	
	private CommandExecuter getExecuter(String body){
		// by default, use amule
		CommandExecuter returnValue = new AmulecmdExecuter();
		String[] words = body.split(" ");
		if("ed".equals(words[0])){
			// default value - amule
		}else if("to".equals(words[0])){
			
		}else{
			
		}
		return returnValue;
	}
}


